import { ElMessage } from 'element-plus';
import { useMarketingApi } from '/@/api/marketing';
import { deepCopy } from '/@/utils';

const { editAdPosition, getAdPositionList } = useMarketingApi();

export const adMainTypeOptions = [
	{ label: '全部', value: '' },
	{ label: '商品', value: 1 },
	{ label: '分类', value: 2 },
	{ label: '优惠券', value: 3 },
	{ label: '活动链接', value: 4 },
	{ label: '白点', value: 5 },
];
export const rules = {
	positionId: [{ required: true, message: '请选择广告位置', trigger: 'change' }],
	type: [{ required: true, message: '请选择广告主体类型', trigger: 'change' }],
	specificContent: [{ required: true, message: '请输入url', trigger: 'blur' }],
	specificContentNum: [{ required: true, message: '请选择商品/分类/优惠券', trigger: 'change' }],
	pcPic: [{ required: true, message: '请选择PC端图片', trigger: 'change' }],
	mobilePic: [{ required: true, message: '请选择移动端图片', trigger: 'change' }],
};
export const useInit = () => {
	const loading = ref(false);
	const page = ref({
		pageSize: 10,
		current: 1,
		total: 0,
	});
	const searchForm = ref({});
	const tableData = ref([]);
	const init = async () => {
		loading.value = true;
		let res = await getAdPositionList({ ...page.value, ...searchForm.value });
		loading.value = false;
		if (res.code !== 200) return;
		const { data, total } = res.data;
		tableData.value = data;
		page.value.total = total;
	};

	onMounted(init);
	return {
		page,
		adMainTypeOptions,
		searchForm,
		loading,
		tableData,
		init,
	};
};

const positionList = ref([]);

export const getAllPosition = async (id) => {
	const loading = ref(false);
	const page = ref({
		pageSize: 99,
		current: 1,
		total: 0,
	});
	loading.value = true;
	let res = await getAdPositionList({ ...page.value, positionId: id });
	loading.value = false;
	if (res.code !== 200) return;
	const { data, total } = res.data;
	positionList.value = data.map((item) => {
		item.specificContentNum = item.specificContent ? Number(item.specificContent) : item.specificContentNum;
		return item;
	});
	page.value.total = total;
	return res.data;
};

export const useEdit = (init) => {
	const isAdd = ref(false);
	const editDialogVisible = ref(false);
	const addDialogVisible = ref(false);
	const dotDialogVisible = ref(false);
	const editItem = ref({});

	return {
		isAdd,
		editDialogVisible,
		addDialogVisible,
		dotDialogVisible,
		editItem,
		positionList,
		async changeStatus({ id, status }) {
			let res = await editAdPosition({ id, status, statusType: 1 });
			if (res.code === 200) {
				ElMessage.success('更改状态成功！');
			} else {
				init();
			}
		},
		toAdd() {
			addDialogVisible.value = true;
			isAdd.value = true;
		},
		async toEdit(row) {
			editItem.value = deepCopy(row);
			isAdd.value = false;
			if (row.type === 5) {
				dotDialogVisible.value = true;
			} else {
				await getAllPosition(row.positionId);
				addDialogVisible.value = true;
			}
		},
	};
};
